//
//  DetailViewController.m
//  DSYDouban
//
//  Created by dllo on 15/12/31.
//  Copyright © 2015年 lanou3g. All rights reserved.
//

#import "DetailViewController.h"
#import "UIImageView+WebCache.h"
#import "DBManager.h"
#import "UserLoginViewController.h"

@interface DetailViewController ()

@property (nonatomic, retain) UIScrollView *scrollView;

@property (nonatomic, retain) UIImageView *imgView;

@property (nonatomic, retain) UILabel *titleNameLable;

@property (nonatomic, retain) UIImageView *dateImageView;

@property (nonatomic, retain) UIImageView *categoryImageView;

@property (nonatomic, retain) UIImageView *owerNameImageView;

@property (nonatomic, retain) UIImageView *addressImageView;

@property (nonatomic, retain) UILabel *start_to_endTimeLabel;

@property (nonatomic, retain) UILabel *categoryLable;

@property (nonatomic, retain) UILabel *owerNameLabel;

@property (nonatomic, retain) UILabel *addressLabel;

@property (nonatomic, retain) UILabel *contentLable;



@property (nonatomic, retain) NSMutableArray *eventArr;

// 当前登录的用户
@property (nonatomic, retain) NSDictionary *user;

@end

@implementation DetailViewController

- (void)dealloc
{
    
    [_scrollView release];
   
    
    [_imgView release];
    [_titleNameLable release];
    
    [_dateImageView release];
    [_start_to_endTimeLabel release];
    [_categoryImageView release];
    [_categoryLable release];
    [_owerNameImageView release];
    [_owerNameLabel release];
    [_addressImageView release];
    [_addressLabel release];
    
    [_contentLable release];
    
    [_eventArr release];
    [_indexPath release];
//    [_contentImage release];
    [_collectionArr release];
    Block_release(_block);
    
    [_user release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self dataHandle];
    
    
    self.navigationItem.title = [_eventArr[_indexPath.row] objectForKey:@"title"];
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIImage *backImage = [UIImage imageNamed:@"btn_nav_back.png"];
    [backImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:backImage style:UIBarButtonItemStylePlain target:self action:@selector(backAction:)];
    self.navigationItem.leftBarButtonItem = backItem;
    [backItem release];
    
    UIBarButtonItem *rightCollect = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"btn_nav_share.png"] style:UIBarButtonItemStylePlain target:self action:@selector(collectActivity1:)];
    self.navigationItem.rightBarButtonItem = rightCollect;
    [rightCollect release];
    
    [self createView];
    
}


- (void)createView {
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(10, 0, self.view.frame.size.width - 20, self.view.frame.size.height - 64)];

    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.contentSize = CGSizeMake(_scrollView.frame.size.width, 1000);
    
//    NSLog(@"%f   %f", _scrollView.frame.size.width, _scrollView.contentSize.width);
    
    
    [self.view addSubview:_scrollView];
    [_scrollView release];
    
    self.titleNameLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 15, _scrollView.frame.size.width, 60)];
    _titleNameLable.text = [_eventArr[_indexPath.row] objectForKey:@"title"];
    _titleNameLable.numberOfLines = 0;
    [_scrollView addSubview:_titleNameLable];
    [_titleNameLable release];
    
    
    CGFloat scroll_W = _scrollView.frame.size.width;

    
    self.imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 80, scroll_W / 3, (scroll_W / 3 - 10) * 1.35)];
    // 添加图片
    NSString *str = [_eventArr[_indexPath.row] objectForKey:@"image"];
    [_imgView sd_setImageWithURL:[NSURL URLWithString:str]];
    [_scrollView addSubview:_imgView];
    [_imgView release];
    
    // 时间的图标和内容添加
    self.dateImageView = [[UIImageView alloc] initWithFrame:CGRectMake(scroll_W / 3 + 5, 80, 25, 25)];
    _dateImageView.image = [UIImage imageNamed:@"icon_date_blue.png"];
    [_scrollView addSubview:_dateImageView];
    [_dateImageView release];
//    _dateImageView.backgroundColor = [UIColor blueColor];
    
    // 取出时间
    NSString *beginTime = [_eventArr[_indexPath.row] objectForKey:@"begin_time"];
    NSString *endTime = [_eventArr[_indexPath.row] objectForKey:@"end_time"];
    
    
    self.start_to_endTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(scroll_W / 3 + 30, _dateImageView.frame.origin.y, scroll_W * 2 / 3 - 30, 25)];
    // 展览时间的显示
    _start_to_endTimeLabel.text = [NSString stringWithFormat:@"%@ -- %@", [beginTime substringWithRange:NSMakeRange(5, 11)], [endTime substringWithRange:NSMakeRange(5, 11)]];
    _start_to_endTimeLabel.font = [UIFont systemFontOfSize:14.0];
    
//    _start_to_endTimeLabel.backgroundColor = [UIColor greenColor];
    [_scrollView addSubview:_start_to_endTimeLabel];
    [_start_to_endTimeLabel release];
    
    
    // 拥有者
    self.owerNameImageView = [[UIImageView alloc] initWithFrame:CGRectMake(scroll_W / 3 + 5, 110, 25, 25)];
    _owerNameImageView.image = [UIImage imageNamed:@"icon_sponsor_blue.png"];
    [_scrollView addSubview:_owerNameImageView];
    [_owerNameImageView release];
    
    self.owerNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(scroll_W / 3 + 30, _owerNameImageView.frame.origin.y, scroll_W * 2 / 3 - 30, 25)];
    _owerNameLabel.text = [[_eventArr[_indexPath.row] objectForKey:@"owner"] objectForKey:@"name"];
    _owerNameLabel.font = [UIFont systemFontOfSize:14.0];
    [_scrollView addSubview:_owerNameLabel];
    [_owerNameLabel release];
    
    // category的添加
    self.categoryImageView = [[UIImageView alloc] initWithFrame:CGRectMake(scroll_W / 3 + 5, 140, 25, 25)];
    _categoryImageView.image = [UIImage imageNamed:@"icon_catalog_blue.png"];
    [_scrollView addSubview:_categoryImageView];
    [_categoryImageView release];
    
    self.categoryLable = [[UILabel alloc] initWithFrame:CGRectMake(scroll_W / 3 + 30, _categoryImageView.frame.origin.y, scroll_W * 2 / 3 - 30, 25)];
//    _categoryLable.backgroundColor = [UIColor greenColor];
    _categoryLable.text = [_eventArr[_indexPath.row] objectForKey:@"category_name"];
    _categoryLable.font = [UIFont systemFontOfSize:14.0];
    [_scrollView addSubview:_categoryLable];
    [_categoryLable release];
    
    // 地址的添加
    self.addressImageView = [[UIImageView alloc] initWithFrame:CGRectMake(scroll_W / 3 + 5, 170, 25, 25)];
    _addressImageView.image = [UIImage imageNamed:@"icon_spot_blue.png"];
    [_scrollView addSubview:_addressImageView];
    [_addressImageView release];
    
    self.addressLabel = [[UILabel alloc] initWithFrame:CGRectMake(scroll_W / 3 + 30, _addressImageView.frame.origin.y, scroll_W * 2 / 3 - 30, 40)];
    _addressLabel.text = [_eventArr[_indexPath.row] objectForKey:@"address"];
    _addressLabel.font = [UIFont systemFontOfSize:14.0];
    _addressLabel.numberOfLines = 0;
    [_scrollView addSubview:_addressLabel];
    [_addressLabel release];
    
    // 显示“活动介绍”
    UILabel *lLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, _imgView.frame.origin.y + _imgView.frame.size.height + 20, scroll_W, 40)];
    lLabel.text = @"活动介绍";
    lLabel.font = [UIFont systemFontOfSize:25];
    [_scrollView addSubview:lLabel];
    [lLabel release];
    
    
    CGFloat contentsHeight = [self contentHeight:scroll_W];
    // 详情介绍内容
    self.contentLable = [[UILabel alloc] initWithFrame:CGRectMake(0, lLabel.frame.origin.y + lLabel.frame.size.height + 10, scroll_W, contentsHeight + 20)];
    _contentLable.font = [UIFont systemFontOfSize:16.0];
    _contentLable.text = [_eventArr[_indexPath.row] objectForKey:@"content"];
    _contentLable.numberOfLines = 0;
    [_scrollView addSubview:_contentLable];
    [_contentLable release];
    
    // 重新修订contentSize的大小
    _scrollView.contentSize = CGSizeMake(scroll_W, _contentLable.frame.origin.y + contentsHeight + 40);
    
    
    
}

// 获取活动介绍内容的高度 (通过显示文字的宽度)
- (CGFloat)contentHeight: (CGFloat)width {
    // 获取内容
    NSString *contents = [_eventArr[_indexPath.row] objectForKey:@"content"];
    
    // 描述文字的大小
    NSDictionary *attribute = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16.0], NSFontAttributeName, nil];
    
    // 获取文字大小
    CGRect rect = [contents boundingRectWithSize:CGSizeMake(width, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:attribute context:nil];
    return rect.size.height;
}

// 数据的加载
- (void)dataHandle {
    
    NSString *path = @"/Users/dllo/Desktop/dsy/UI/DSYDouban/DSYDouban/activitylist.txt";
    
    NSData *data = [NSData dataWithContentsOfFile:path];
    
    id result1 = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    
    self.eventArr = [NSMutableArray arrayWithArray:[result1 objectForKey:@"events"]];
    
//    NSLog(@"%@", _eventArr);
}

// 右侧收藏按钮的监听事件
- (void)collectActivity: (UIBarButtonItem *)buttonItem {
    buttonItem.image = [UIImage imageNamed:@"btn_nav_share@2x.png"];

    
    if ([_collectionArr containsObject:_titleNameLable.text]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示消息" message:@"该活动已经收藏" preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:alert animated:YES completion:^{
            [alert dismissViewControllerAnimated:YES completion:^{
                
            }];
        }];
        
        
        
//        NSString *sql = [NSString stringWithFormat:@"insert into activityCollection "]
        
    } else {
        [_collectionArr addObject:_titleNameLable.text];
        // block传值
        self.block(_collectionArr);
        
        // 消息提示
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示消息" message:@"您成功成收藏该活动" preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:alert animated:YES completion:^{
            [NSThread sleepForTimeInterval:1];
            [alert dismissViewControllerAnimated:YES completion:^{
                
            }];
        }];
    }
    
//    [self collectActivity:buttonItem];
    
}

// 右侧收藏按钮的监听事件
- (void)collectActivity1: (UIBarButtonItem *)buttonItem {
    if ([self hasCurrentUser] == YES) {

        NSLog(@"收藏成功");
        // 查看是否被当前用户收藏
        if ([self isCollected] == NO) {
            
            // 将当前收藏的活动插入数据库中
            NSString *insertStr = [NSString stringWithFormat:@"insert into activityCollection(name, username) values('%@', '%@')", _titleNameLable.text, [_user objectForKey:@"username"]];
            
            [[DBManager createDB] insert:insertStr];
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示消息" message:@"您成功收藏该活动" preferredStyle:UIAlertControllerStyleAlert];
            
            [self presentViewController:alert animated:YES completion:^{
                [NSThread sleepForTimeInterval:1];
                [alert dismissViewControllerAnimated:YES completion:^{
                    
                }];
            }];
            
            
        } else {
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示消息" message:@"该活动已经收藏" preferredStyle:UIAlertControllerStyleAlert];
            
            [self presentViewController:alert animated:YES completion:^{
                [NSThread sleepForTimeInterval:1];
                [alert dismissViewControllerAnimated:YES completion:^{
                    
                }];
            }];
            
        }
        
    } else {  // 当没有检查到用户，就跳转登录页面
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示消息" message:@"您未登录，请登录" preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:alert animated:YES completion:^{
            [NSThread sleepForTimeInterval:1];
            [alert dismissViewControllerAnimated:YES completion:^{
                
                UserLoginViewController *userLoginVC = [[UserLoginViewController alloc] init];
                [self.navigationController pushViewController:userLoginVC animated:YES];
                [userLoginVC release];
            }];
        }];
    }
}

// 查看当前登录的用户
- (BOOL) hasCurrentUser {
    
    self.user = [[DBManager createDB] currentUser];
    
    if ([_user objectForKey:@"username"] != NULL) {
        return YES;
    } else {
        return NO;
    }
    
}



// 查看是否被当前用户收藏
- (BOOL) isCollected {
    NSLog(@"%@,    %@", _titleNameLable.text, [_user objectForKey:@"username"]);
    // 通过当前的标号
    NSString *isCollectedStr = [NSString stringWithFormat:@"select * from activityCollection where name = '%@' and username = '%@'", _titleNameLable.text, [_user objectForKey:@"username"]];
    
    NSArray *arr = [[DBManager createDB] selectActivity:isCollectedStr];
    
    NSLog(@"%ld", arr.count);
    
    if (arr.count == 0) {
        return NO;   // 没有被收藏
    } else {
        return YES;  // 已经被收藏
    }
}

// 返回键
- (void)backAction: (UIBarButtonItem *)buttonItem {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
